package com.zy.je.common.mybatis.ext.plugin;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zy.je.common.core.model.LoginUser;
import com.zy.je.common.mybatis.ext.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.util.ClassUtils;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Optional;

/**
 * MybatisPlus 自动填充配置
 *
 * @author zy
 */
@Slf4j
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    private static String DELETE_FLAG_FIELD_NAME = "deleteFlag";
    private static String CREATE_TIME_FIELD_NAME = "createTime";
    private static String UPDATE_TIME_FIELD_NAME = "updateTime";
    private static String DELETE_TIME_FIELD_NAME = "deleteTime";
    private static String CREATE_BY_FIELD_NAME = "createBy";
    private static String UPDATE_BY_FIELD_NAME = "updateBy";
    private static String DELETE_BY_FIELD_NAME = "deleteBy";
    private static String CREATE_USERNAME_FIELD_NAME = "createUsername";
    private static String UPDATE_USERNAME_FIELD_NAME = "updateUsername";
    private static String DELETE_USERNAME_FIELD_NAME = "deleteUsername";

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("mybatis plus start insert fill ....");
//		LocalDateTime now = LocalDateTime.now();
        Date now = new Date();
        LoginUser currentUser = LoginUserUtil.getCurrentUser();

        fillValIfNullByName(CREATE_TIME_FIELD_NAME, now, metaObject, false);
//        fillValIfNullByName(UPDATE_TIME_FIELD_NAME, now, metaObject, false);
        fillValIfNullByName(CREATE_BY_FIELD_NAME, getUserId(currentUser), metaObject, false);
        fillValIfNullByName(UPDATE_BY_FIELD_NAME, getUserId(currentUser), metaObject, false);
        //逻辑删除字段设置默认值
        fillValIfNullByName(DELETE_FLAG_FIELD_NAME, "0", metaObject, false);
        fillValIfNullByName(CREATE_USERNAME_FIELD_NAME, getUserName(currentUser), metaObject, false);
        //fillValIfNullByName(UPDATE_USER_NAME_FIELD_NAME, getUserName(currentUser), metaObject, false);
    }

    private String getUserId(LoginUser currentUser) {
        return Optional.ofNullable(currentUser)
                .map(it -> it.getId())
                .orElse(null);
    }

    private String getUserName(LoginUser currentUser) {
        return Optional.ofNullable(currentUser)
                .map(it -> it.getUserName())
                .orElse(null);
    }



    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("mybatis plus start update fill ....");
//		LocalDateTime now = LocalDateTime.now();
        Date now = new Date();
        LoginUser currentUser = LoginUserUtil.getCurrentUser();

        fillValIfNullByName(UPDATE_TIME_FIELD_NAME, now, metaObject, true);
        fillValIfNullByName(UPDATE_BY_FIELD_NAME, getUserId(currentUser), metaObject, true);
        fillValIfNullByName(UPDATE_USERNAME_FIELD_NAME, getUserName(currentUser), metaObject, false);
    }

    /**
     * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
     *
     * @param fieldName  属性名
     * @param fieldVal   属性值
     * @param metaObject MetaObject
     * @param isCover    是否覆盖原有值,避免更新操作手动入参
     */
    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
        // 1. 没有 get 方法
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        // 2. 如果用户有手动设置的值
        Object userSetValue = metaObject.getValue(fieldName);
        String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
        if (StrUtil.isNotBlank(setValueStr) && !isCover) {
            return;
        }
        // 3. field 类型相同时设置
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }

//	/**
//	 * 获取 spring security 当前的用户
//	 * @return 当前用户
//	 */
//	private UserDTO getCurrentUser() {
//        //从Header中获取用户信息
//        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        if (null == servletRequestAttributes) {
//            return null;
//        }
//        HttpServletRequest request = servletRequestAttributes.getRequest();
//        if (null == request) {
//            return null;
//        }
//
//        String userStr = request.getHeader("user");
//        if (!ObjectUtil.isEmpty(userStr)) {
//            JSONObject userJsonObject = new JSONObject(userStr);
//            UserDTO userDTO = new UserDTO();
//            userDTO.setUsername(URLUtil.decode(userJsonObject.getStr("username")));
//            userDTO.setId(userJsonObject.getStr("id"));
//            userDTO.setClientId(userJsonObject.getStr("client_id"));
//            userDTO.setRoles(Convert.toList(String.class,userJsonObject.get("authorities")));
//            userDTO.setTenantId(userJsonObject.getStr("tenant_id"));
//            userDTO.setSystemIds(userJsonObject.getStr("system_ids"));
//            return userDTO;
//
//        }
//        return null;
//	}
//
//    private Object getUserId(UserDTO currentUser) {
//        return Optional.ofNullable(currentUser)
//                .map(it -> it.getId())
//                .orElse(null);
//    }
//
//    private Object getUserName(UserDTO currentUser) {
//        return Optional.ofNullable(currentUser)
//                .map(it -> it.getUsername())
//                .orElse(null);
//    }

}
